import React, { PureComponent, Fragment, Suspense } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';

import { Row, Col, Card, Form, Input, Button, Timeline } from 'antd';

import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Pie, WaterWave, Gauge, TagCloud } from '@/components/Charts';

import styles from './Analysis.less';

// import OfflineData from '@/pages/Dashboard/OfflineData'

const OfflineData = React.lazy(() => import('./OfflineData'));

const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];

/* eslint react/no-multi-comp:0 */
@connect(({ analysisRule, loading }) => ({
  analysisRule,
  loading: loading.models.analysisRule,
}))
@Form.create()
class Analysis extends PureComponent {
  state = {
    dataTradeList: {},
    currentTabKey: '',
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      stockId: '',
      orderField: '', // 排序字段
      orderType: 0, // 排序方向
    }, // 查询菜单栏   查询参数

    scoreHistoryParam: {
      type: '',
    },
    hover: '',
    modalVisible: false,
    updateModalVisible: false,

    selectedRows: [],

    stepFormValues: {},
  };

  columns = [
    {
      title: '',
      dataIndex: 'id',
      render: text => <span>{}</span>,
    },
    {
      title: '股票代码',
      dataIndex: 'stockId',
    },
    {
      title: '财报时间 ',
      dataIndex: 'earningsDate',
    },
    {
      title: '涨跌幅%',
      dataIndex: 'changeRate',
    },
    {
      title: '涨跌幅日期',
      dataIndex: 'changeRateDate',
    },
  ];

  handleTabChange = key => {
    this.setState({
      currentTabKey: key,
    });
  };

  // 默认加载数据-起始方法
  render() {
    const {
      analysisRule: { scoreData, scoreHistoryData },
      loading,
      analysisRule,
    } = this.props;
    // const { chart } = this.props;
    const { currentTabKey } = this.state;

    const { offlineData } = analysisRule;

    const activeKey = currentTabKey || (offlineData[0] && offlineData[0].name);

    const newData = [];
    for (let i = 0; i < scoreHistoryData.data.length; i += 1) {
      newData.push({
        x: new Date(scoreHistoryData.data[i].date).getTime(),
        y1: scoreHistoryData.data[i].sum,
      });
    }
    if (scoreData.data.length < 3) {
      return (
        <PageHeaderWrapper title="大盘健康度">
          <Card bordered={false} />
        </PageHeaderWrapper>
      );
    }
    return (
      <PageHeaderWrapper title="大盘健康度">
        <Card bordered={false}>
          <div>
            <Row>
              <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
                <Col span={14}>
                  <div
                    className={
                      this.state.hover === 1 ? styles.gaugeStyleTransform : styles.gaugeStyle
                    }
                    onClick={this.switchTimelineChart.bind(this, scoreData.data[0].type)}
                    onMouseEnter={this.onMouseEnter.bind(this, scoreData.data[0].type)}
                    onMouseLeave={this.onMouseLeave.bind(this, 4)}
                  >
                    <Gauge
                      title="今日健康度"
                      height={180}
                      percent={scoreData.data[0].sum}
                      color={this.renderGaugeColor(scoreData.data[0].sum)}
                      bgColor="#F0F2F5"
                    />
                    <h1 style={{ fontSize: 16, textAlign: 'center', paddingTop: 10 }}>QQQ</h1>
                    <h1 style={{ fontSize: 12, textAlign: 'center' }}>
                      {scoreData.data[0].date.substr(5, 5)}
                    </h1>
                  </div>
                </Col>
                <Col span={10}>
                  <div className={styles.tableListForm}>
                    {this.renderTimeline(scoreData.data[0])}{' '}
                  </div>
                </Col>
              </Col>

              <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
                <Col span={14}>
                  <div
                    className={
                      this.state.hover === 2 ? styles.gaugeStyleTransform : styles.gaugeStyle
                    }
                    onClick={this.switchTimelineChart.bind(this, scoreData.data[1].type)}
                    onMouseEnter={this.onMouseEnter.bind(this, scoreData.data[1].type)}
                    onMouseLeave={this.onMouseLeave.bind(this, 4)}
                  >
                    <Gauge
                      title="今日健康度"
                      height={180}
                      percent={scoreData.data[1].sum}
                      color={this.renderGaugeColor(scoreData.data[1].sum)}
                      bgColor="#F0F2F5"
                    />
                    <h1 style={{ fontSize: 16, textAlign: 'center', paddingTop: 10 }}>上证指数</h1>
                    <h1 style={{ fontSize: 12, textAlign: 'center' }}>
                      {scoreData.data[1].date.substr(5, 5)}
                    </h1>
                  </div>
                </Col>
                <Col span={10}>
                  <div className={styles.tableListForm}>
                    {this.renderTimeline(scoreData.data[1])}
                  </div>
                </Col>
              </Col>

              <Col xl={7} lg={24} md={24} sm={24} xs={24} offset={1}>
                <Col span={14}>
                  <div
                    className={
                      this.state.hover === 3 ? styles.gaugeStyleTransform : styles.gaugeStyle
                    }
                    onClick={this.switchTimelineChart.bind(this, scoreData.data[2].type)}
                    onMouseEnter={this.onMouseEnter.bind(this, scoreData.data[2].type)}
                    onMouseLeave={this.onMouseLeave.bind(this, 4)}
                  >
                    <Gauge
                      title="今日健康度"
                      height={180}
                      percent={scoreData.data[2].sum}
                      color={this.renderGaugeColor(scoreData.data[2].sum)}
                      bgColor={!this.state.hover ? '#F0F2F5' : '#F0F2F5'}
                      // bgColor={!this.state.hover?"#F0F2F5":"#11111188"}
                    />
                    <h1 style={{ fontSize: 16, textAlign: 'center', paddingTop: 10 }}>恒生指数</h1>
                    <h1 id="stock4" style={{ fontSize: 12, textAlign: 'center' }}>
                      {scoreData.data[2].date.substr(5, 5)}
                    </h1>
                  </div>
                </Col>
                <Col span={10}>
                  <div className={styles.tableListForm}>
                    {this.renderTimeline(scoreData.data[2])}
                  </div>
                </Col>
              </Col>
            </Row>
          </div>
          <Suspense fallback={null}>
            <OfflineData
              activeKey={activeKey}
              loading={loading}
              offlineData={offlineData}
              offlineChartData={newData}
              tickInterval={60 * 60 * 1000 * 24 * 5}
              titleMap={{
                y1: '历史健康度',
              }}
              handleTabChange={this.handleTabChange}
            />
          </Suspense>
          <div className={styles.tableList} />
        </Card>
      </PageHeaderWrapper>
    );
  }

  onMouseEnter(param) {
    this.setState({
      hover: param,
    });
  }

  onMouseLeave(param) {
    this.setState({
      hover: param,
    });
  }

  // 加载完 之后 再加载 此 方法
  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues, listLoading, scoreHistoryParam } = this.state;
    dispatch({
      type: 'analysisRule/GetUSScore',
      payload: formValues,
    });
    scoreHistoryParam.type = 1;
    dispatch({
      type: 'analysisRule/GetUSScoreHistory',
      payload: scoreHistoryParam,
    });
  }

  // 绘制仪表盘颜色
  renderGaugeColor(sum) {
    if (sum >= 70) {
      return '#95de64';
    }
    if (sum >= 30) {
      return '#FF9933';
    }
    return '#FF0033';
  }

  switchTimelineChart(param) {
    const {
      analysisRule: { scoreData },
      dispatch,
    } = this.props;
    const { scoreHistoryParam } = this.state;
    scoreHistoryParam.type = param;
    // alert(param);
    dispatch({
      type: 'analysisRule/GetUSScoreHistory',
      payload: scoreHistoryParam,
    });
  }

  // 改变每页条数和当前页
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    formValues.pageNum = pagination.current;
    formValues.pageSize = pagination.pageSize;

    if (sorter.field) {
      // 排序参数
      formValues.orderField = `${sorter.field}`;
      if (sorter.order == 'ascend') {
        formValues.orderType = 2; // 升序
      } else if (sorter.order == 'descend') {
        formValues.orderType = 1; // 降序
      } else {
        formValues.orderType = 0; // 不排序
      }
    }
    const params = {
      ...formValues,
      ...filters,
    };

    dispatch({
      type: 'analysisRule/GetRoyaltiesList',
      payload: params1,
    });
  };

  renderTimeline(param) {
    if (typeof param === 'undefined') return;
    const newData = [];
    const { length } = param.scores;
    if (length < 3) return;

    const str = param.scores.substr(1, length - 2);
    const arr = str.split(',');
    for (let i = 0; i < arr.length; i += 1) {
      if (arr[i] > 0) {
        newData.push('green');
      } else {
        newData.push('red');
      }
    }
    return (
      <Timeline className={styles.timelineStyle}>
        <Timeline.Item color={newData[0]}>5个交易日跌7%</Timeline.Item>
        <Timeline.Item color={newData[1]}>跌破55均线</Timeline.Item>
        <Timeline.Item color={newData[2]}>跌破20日最低价格</Timeline.Item>
        <Timeline.Item color={newData[3]}>macd 顶底信号</Timeline.Item>
        <Timeline.Item color={newData[4]}>阶梯线</Timeline.Item>
      </Timeline>
    );
  }
}

export default Analysis;
